const {
  powerSet
} = require('../../utils/power-set')
var pathMap
var app = getApp()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    show: Boolean,
    goodPopId: Number,
  },
  /**
   * 组件的初始数据
   */
  data: {
    goodsList: [{
      id: 8,
      image: 'https://picsum.photos/id/9/115/115',
      title: '【黑猪肉老面手工小笼包】一口大满足 皮箱肉馅 翼龙现包陪伴你三餐啊啊啊啊啊啊啊啊',
      dec: '精选无抗黑猪肉，不掺杂其他肉类，拒绝边角料啊啊啊啊',
      price: '39.9',
      num: '102222222'
    }, ],
    detailData: {},
    isShow: false,
    fatherShow: false,
    payShow: false,
    quantity: 1,
    goods_id: null,
  },
  observers: {
    goodPopId: function (v) {
      if (v) {
        const e = {
          currentTarget: {
            dataset: {
              good: {
                goods_id: v
              }
            }
          }
        }
        this.getData()
        this.geSkuData(e)
      }
    },
    show: function (e) {
      if (e) {
        const item = {
          currentTarget: {
            dataset: {
              good: {
                goods_id: 32
              }
            }
          }
        }
        this.geSkuData(item)
        // liveGoodsList({
        //   id: app.liveInfo.live_id
        // }).then(res => {
        //   this.setData({
        //     goodsList: res.data.data
        //   })
        // })
      }
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // getData(){
    //   liveGoodsList({
    //     id: app.liveInfo.live_id
    //   }).then(res => {
    //     this.setData({
    //       goodsList: res.data.data,
    //       isShow:true
    //     })
    //   })
    // },

    async geSkuData(e) {
      if (e.currentTarget.dataset.good.hide_price) return
      if (e.currentTarget.dataset.good.is_sell_out) return
      const id = e.currentTarget.dataset.good.goods_id
      // const res = await goodsInfoGet({
      //   id
      // })
      let _data = {
        img: [{
          id: 1,
          img_url: 'https://picsum.photos/id/10/500/500'
        }],
        info: {
          c_id: 0,
          default_spec: "经典黑 S",
          goods_des: "",
          goods_name: "设计感扭结开叉不规则显瘦T恤B2500",
          goods_sn: "YSTX",
          id: 693,
          img_url: "https://picsum.photos/id/10/500/500",
          price: 59,
          status: 1,
          weight: 0,
        },
        skus: [{
            default_show: 0,
            id: 2839,
            img_url: "https://picsum.photos/id/10/500/500",
            price: "59.00",
            sku_sn: "YSTXHS",
            specs: [{
              name: "颜色",
              value_name: "经典黑"
            }, {
              name: "尺码",
              value_name: "S"
            }],
            stock_num: 9999,
          },
          {
            default_show: 0,
            id: 2840,
            img_url: "https://picsum.photos/id/11/500/500",
            price: "59.00",
            sku_sn: "YSTXHM",
            specs: [{
              name: "颜色",
              value_name: "经典黑"
            }, {
              name: "尺码",
              value_name: "M"
            }],
            stock_num: 9999
          },
          {
            default_show: 0,
            id: 2841,
            img_url: "https://picsum.photos/id/12/500/500",
            price: "59.00",
            sku_sn: "YSTXHL",
            specs: [{
              name: "颜色",
              value_name: "经典黑"
            }, {
              name: "尺码",
              value_name: "L"
            }],
            stock_num: 9999
          },
          {
            default_show: 0,
            id: 2842,
            img_url: "https://picsum.photos/id/13/500/500",
            price: "59.00",
            sku_sn: "YSTXHXL",
            specs: [{
              name: "颜色",
              value_name: "经典黑"
            }, {
              name: "尺码",
              value_name: "XL"
            }],
            stock_num: 9999
          },
          {
            default_show: 0,
            id: 2843,
            img_url: "https://picsum.photos/id/14/500/500",
            price: "59.00",
            sku_sn: "YSTXNS",
            specs: [{
              name: "颜色",
              value_name: "奶油白"
            }, {
              name: "尺码",
              value_name: "S"
            }],
            stock_num: 9999
          },
          {
            default_show: 0,
            id: 2844,
            img_url: "https://picsum.photos/id/15/500/500",
            price: "59.00",
            sku_sn: "YSTXNM",
            specs: [{
              name: "颜色",
              value_name: "奶油白"
            }, {
              name: "尺码",
              value_name: "M"
            }],
            stock_num: 9999
          },
          {
            default_show: 0,
            id: 2845,
            img_url: "https://picsum.photos/id/16/500/500",
            price: "59.00",
            sku_sn: "YSTXNL",
            specs: [{
              name: "颜色",
              value_name: "奶油白"
            }, {
              name: "尺码",
              value_name: "L"
            }],
            stock_num: 9999
          },
          {
            default_show: 0,
            id: 2846,
            img_url: "https://picsum.photos/id/17/500/500",
            price: "59.00",
            sku_sn: "YSTXNXL",
            specs: [{
              name: "颜色",
              value_name: "奶油白"
            }, {
              name: "尺码",
              value_name: "XL"
            }],
            stock_num: 9999
          },
        ],
        specs: [{
            name: "颜色",
            values: [{
                name: "经典黑",
                id: 2100,
                selected: true
              },
              {
                name: "奶油白",
                id: 2101,
                selected: false
              }
            ]
          },
          {
            name: "尺码",
            values: [{
                name: "S",
                id: 2102,
                selected: true
              },
              {
                name: "M",
                id: 2103,
                selected: false
              },
              {
                name: "L",
                id: 2104,
                selected: false
              }, {
                name: "XL",
                id: 2105,
                selected: false
              }
            ]
          },
        ]
      }
      this.setData({
        detailData: _data,
        goods_id: e.currentTarget.dataset.good.goods_id
      })
      pathMap = this.getPathMap(this.data.detailData)
      this.initDisabledState(this.data.detailData.specs, pathMap)
      this.submitSku()
      this.setData({
        sonShow: true
      })
    },
    getPathMap(goods) {
      const pathMap = {}
      // 1. 得到所有有效的Sku集合 
      const effectiveSkus = goods.skus.filter(sku => sku.stock_num > 0)
      // 2. 根据有效的Sku集合使用powerSet算法得到所有子集 [1,2] => [[1], [2], [1,2]]
      effectiveSkus.forEach(sku => {
        // 2.1 获取可选规格值数组
        const selectedValArr = sku.specs.map(val => val.value_name)
        // 2.2 获取可选值数组的子集
        const valueArrPowerSet = powerSet(selectedValArr)
        // 3. 根据子集生成路径字典对象
        // 3.1 遍历子集 往pathMap中插入数据
        valueArrPowerSet.forEach(arr => {
          // 根据Arr得到字符串的key，约定使用-分割 ['蓝色'，'美国'] => '蓝色-美国'
          const key = arr.join('-')
          // 给pathMap设置数据
          if (pathMap[key]) {
            pathMap[key].push(sku.id)
          } else {
            pathMap[key] = [sku.id]
          }
        })
      })
      return pathMap
    },
    initDisabledState(specs, pathMap) {
      specs.forEach(item => {
        item.values.forEach(val => {
          // 路径字典中查找是否有数据 有-可以点击 没有-禁用
          val.disabled = !pathMap[val.name]
        })
      })
      let data = this.data.detailData
      data.specs = specs
      this.setData({
        detailData: data
      })
    },
    changeSku(e) {
      let val = e.currentTarget.dataset.val
      let item = e.currentTarget.dataset.item
      if (val.disabled) {
        return
      }
      // 点击的是未选中，把同一个规格的其他取消选中，当前点击项选中，点击的是已选中，直接取消
      let dataStmp = this.data.detailData
      const findRes = dataStmp.specs.find(resItem => resItem.name === item.name)
      const findValRes = findRes.values.find(resItem => resItem.id === val.id)
      if (val.selected) {
        findValRes.selected = false
      } else {
        this.setData({
          payShow: false
        })
        findRes.values.forEach(valItem => valItem.selected = false)
        findValRes.selected = true
      }
      this.setData({
        detailData: dataStmp
      })
      this.submitSku()
    },
    submitSku() {
      this.setData({
        goodsSku: '',
        payShow: false,
        stock_num: ''
      })
      this.updateDisabledState(this.data.detailData.specs, pathMap)
      const index = this.getSelectedValues(this.data.detailData.specs).findIndex(item => item === undefined)
      if (index > -1) {
        this.setData({
          payShow: true
        })
      } else {
        const key = this.getSelectedValues(this.data.detailData.specs).join('-')
        const skuIds = pathMap[key]
        //以skuId作为匹配项去goods.value.skus数组中查找
        const skuObj = this.data.detailData.skus.find(item => item.id === skuIds[0])
        let changeSku = skuObj.specs.map(item => item.value_name).join(',')
        this.setData({
          stock_num: skuObj.stock_num,
          goodsSku: changeSku,
          goodsPrice: skuObj.price,
          goodsImg: skuObj.img_url,
          skuObj
        })
      }
    },
    getSelectedValues(specs) {
      const arr = []
      specs.forEach(spec => {
        const selectedVal = spec.values.find(value => value.selected)
        arr.push(selectedVal ? selectedVal.name : undefined)
      })
      return arr
    },
    updateDisabledState(specs, pathMap) {
      // 约定：每一个按钮的状态由自身的disabled进行控制
      specs.forEach((item, i) => {
        const selectedValues = this.getSelectedValues(specs)
        item.values.forEach(val => {
          // if (val.selected) return
          // const _seletedValues = [...selectedValues]
          selectedValues[i] = val.name
          const key = selectedValues.filter(value => value).join('-')
          // 路径字典中查找是否有数据 有-可以点击 没有-禁用
          val.disabled = !pathMap[key]
        })
      })
      let data = this.data.detailData
      data.specs = specs
      this.setData({
        detailData: data
      })
    },
    setQuantity(e) {
      if (this.data.quantity <= 1 && e.currentTarget.dataset.v === -1) {
        return wx.showToast({
          title: '数量最少为1',
          icon: 'none'
        })
      }
      this.setData({
        quantity: this.data.quantity + e.currentTarget.dataset.v
      })
    },
    onClose() {
      this.setData({
        sonShow: false
      })
    },
    popScroll(e) {
      let num = e.detail.scrollTop
      if (num >= 300) {
        this.setData({
          popTop: true
        })
      } else {
        this.setData({
          popTop: false
        })
      }
    },
    async cartPay() {
      app.globalData.address_id = ''
      app.globalData.confirmData.quantity = this.data.quantity
      app.globalData.confirmData.price = this.data.skuObj.price
      app.globalData.confirmData.sku_id = this.data.skuObj.id
      app.globalData.confirmData.goods_id = this.data.goods_id
      app.globalData.confirmData.live_id = app.liveInfo.live_id
      app.globalData.confirmData.form_type = 2
      app.globalData.isActive = false
      app.globalData.couponList = []
      await wx.navigateTo({
        url: '/pages/confirmOrder/index',
      })
    },
    //加入购物车
    // async addCart() {
    //   let skuObj = this.data.skuObj
    //   const res = await goodsCartAdd({
    //     goods_id: 163,
    //     sku_id: skuObj.id,
    //     price: skuObj.price,
    //     quantity: this.data.quantity,
    //     group_buy_id: this.data.id
    //   })
    //   if (res.data.code === 1) {
    //     //amount: num ,cart_ids:[num,...] ,num: num
    //     const goods_cart = this.data.goods_cart
    //     goods_cart.amount = _addNum(goods_cart.amount, skuObj.price * this.data.quantity, '+')
    //     goods_cart.cart_ids = [...new Set([...goods_cart.cart_ids, res.data.data.id])]
    //     goods_cart.num = _addNum(goods_cart.num, this.data.quantity, '+')
    //     this.setData({
    //       goods_cart,
    //       sonShow: false
    //     })

    //   } else {
    //     this.setData({
    //       sonShow: false
    //     })
    //     wx.showToast({
    //       title: res.data.message,
    //       icon: 'none'
    //     })
    //   }
    // },


    // -----
  }
})